<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true">
      <el-form-item label="试卷名称：">
        <el-autocomplete
          v-model="queryParam.paperName"
          :fetch-suggestions="querySearch"
          placeholder="请输入试卷名称"
          clearable
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="年级：">
        <el-select
          v-model="queryParam.level"
          placeholder="年级"
          @change="levelChange"
          clearable
          @clear="clearLevel"
          class="select"
        >
          <el-option
            v-for="item in levelEnum"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学科：">
        <el-select v-model="queryParam.subjectId" clearable class="select">
          <el-option
            v-for="item in subjectFilter"
            :key="item.id"
            :value="item.id"
            :label="item.name + ' ( ' + item.levelName + ' )'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="试卷类型：">
        <el-select v-model="queryParam.paperType" clearable class="select">
          <el-option
            v-for="item in paperTypeEnum"
            :key="item.key"
            :value="item.key"
            :label="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">查询</el-button>
        <router-link :to="{ path: '/exam/paper/edit' }" class="link-left">
          <el-button type="primary">添加</el-button>
        </router-link>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="changeTableSort"
    >
      <el-table-column
        prop="subjectId"
        label="学科"
        width="120px"
        :formatter="subjectFormatter"
        show-overflow-tooltip
      />
      <el-table-column prop="name" label="名称" show-overflow-tooltip />
      <el-table-column prop="score" label="试卷总分" width="100px" />
      <el-table-column prop="difficult" width="80px" label="难度" :sortable="'custom'"/>
      <el-table-column prop="paperType" label="试卷类型" width="100px">
        <template slot-scope="{ row }">
          {{ paperTypeFormat(row.paperType) }}
        </template>
      </el-table-column>

      <el-table-column
        prop="suggestTime"
        label="建议时长(分钟)"
        width="120px"
      />
      <el-table-column
        prop="limitStartTime"
        label="开始时间"
        width="165px"
        :sortable="'custom'"
      />
      <el-table-column
        prop="limitEndTime"
        label="结束时间"
        width="165px"
        :sortable="'custom'"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="165px"
        :sortable="'custom'"
      />
      <el-table-column label="操作" align="center" width="160px">
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            @click="
              $router.push({ path: '/exam/paper/edit', query: { id: row.id } })
            "
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            @click="deletePaper(row)"
            class="link-left"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParam.pageIndex"
      :limit.sync="queryParam.pageSize"
      @pagination="search"
    />
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions, mapMutations } from "vuex";
import Pagination from "@/components/Pagination";
import examPaperApi from "@/api/examPaper";
import subjectApi from "@/api/subject";

export default {
  components: { Pagination },
  data() {
    return {
      queryParam: {
        paperName: null,
        level: null,
        subjectId: null,
        pageIndex: 1,
        pageSize: 10,
        paperType: null,
        sort: "create_time desc"
      },
      subjectFilter: null,
      subjects: null,
      listLoading: true,
      tableData: [],
      total: 0,
    };
  },
  mounted() {
    this.$nextTick(() => {
      let _this = this;
      subjectApi.list().then((re) => {
        _this.subjects = re.response;
        _this.setSubjects(re.response);
        _this.subjectFilter = _this.subjects;
      });
      // this.initSubject();
      this.search();
      this.initPaperNameList();
    });
  },
  methods: {
    // initPaperNameList() {
    //   examPaperApi.paperNameList().then((data) => {
    //     const re = data.response;
    //     let newList = [];
    //     re.map((item) => {
    //       newList.push({
    //         value: item,
    //       });
    //     });
    //     this.paperNameList = newList;
    //   });
    // },
    changeTableSort(column) {
      //获取字段名称和排序类型
      var fieldName = column.prop;
      var sortingType = column.order;
      this.queryParam.pageIndex = 1;
      let x = "";
      if (fieldName == "createTime") {
        x = "create_time";
      } else if (fieldName == "limitStartTime") {
        x = "limit_start_time";
      } else if (fieldName == "limitEndTime") {
        x = "limit_end_time";
      } else if (fieldName = "difficult") {
        x = "difficult";
      }
      if (sortingType == "descending") {
        this.queryParam.sort = x + " desc";
      } else {
        this.queryParam.sort = x + " asc";
      }
      this.search();
    },
    querySearch(queryString, cb) {
      var paperNameList = this.paperNameList;
      var results = queryString
        ? paperNameList.filter(this.createFilter(queryString))
        : paperNameList;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (item) => {
        return (
          item.value.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        );
      };
    },
    submitForm() {
      this.queryParam.pageIndex = 1;
      this.search();
    },
    search() {
      this.listLoading = true;
      examPaperApi.pageList(this.queryParam).then((data) => {
        const re = data.response;
        this.tableData = re.list;
        this.total = re.total;
        this.queryParam.pageIndex = re.pageNum;
        this.listLoading = false;
      });
    },
    deletePaper(row) {
      this.$confirm("是否删除试卷?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let _this = this;
        examPaperApi.deletePaper(row.id).then((re) => {
          if (re.code === 1) {
            _this.search();
            _this.$message.success(re.message);
          } else {
            _this.$message.error(re.message);
          }
        });
      });
    },
    levelChange() {
      this.queryParam.subjectId = null;
      this.subjectFilter = this.subjects.filter(
        (data) => data.level === this.queryParam.level
      );
    },
    subjectFormatter(row, column, cellValue, index) {
      return this.subjectEnumFormat(cellValue);
    },
    paperTypeFormat(cellValue) {
      return this.enumFormat(this.paperTypeEnum, cellValue);
    },
    clearLevel() {
      this.subjectFilter = this.subjects;
    },
    ...mapActions("exam", {
      initSubject: "initSubject",
      initPaperNameList: "initPaperNameList",
    }),
    ...mapMutations("exam", ["setSubjects", "setPaperNameList"]),
  },
  computed: {
    ...mapGetters("enumItem", ["enumFormat"]),
    ...mapState("enumItem", {
      levelEnum: (state) => state.user.levelEnum,
    }),
    ...mapState("enumItem", {
      paperTypeEnum: (state) => state.exam.examPaper.paperTypeEnum,
    }),
    ...mapGetters("exam", ["subjectEnumFormat"]),
    // ...mapState("exam", { subjects: (state) => state.subjects }),
    ...mapState("exam", { paperNameList: (state) => state.paperNameList }),
  },
};
</script>

<style lang="scss">
.select {
  width: 190px;
}
.text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
